package edu.pku.sei.modeler.uml.commands.sequence;

import org.eclipse.draw2d.geometry.Rectangle;

import edu.pku.sei.modeler.model.common.MetaTypedList;
import edu.pku.sei.modeler.model.core.MetaModelElement;
import edu.pku.sei.modeler.model.structure.MetaNode;
import edu.pku.sei.modeler.model.uml.BasicInteractions.Interaction;
import edu.pku.sei.modeler.model.uml.Fragments.InteractionUse;
import edu.pku.sei.modeler.model.uml.Kernel.Comment;
import edu.pku.sei.modeler.uml.commands.NestedElementCreateCommand;

public class UMLLifelineCreateCommand extends NestedElementCreateCommand {

	public UMLLifelineCreateCommand(MetaNode node, MetaNode hostNode,
			Rectangle constraint) {
		super(node, hostNode, constraint);
	}

	@Override
	public boolean canExecute() {
		return super.canExecute()
				&& fatherNode.getModelElement() instanceof Interaction;
	}

	@Override
	protected void updateModelElement() {
		MetaModelElement modelElement = this.node.getModelElement();
		Interaction interaction = (Interaction) fatherNode.getModelElement();
		interaction.getLifeline().add(modelElement);
	}

	@Override
	protected void undoModelElement() {
		Interaction interaction = (Interaction) fatherNode.getModelElement();
		interaction.getLifeline().remove(node.getModelElement());
	}

	@Override
	protected void updateNodeBounds() {
		super.updateNodeBounds();
	}

	
	protected void updateGraphNode() {
		// Yang Yuanzu: Ensure the Lifeline layer is below the InteractionUse layer.
		// which means, we insert the Lifeline MetaNode in front of the ones of InteractionUse.
		MetaTypedList list = fatherNode.getSubNodes();
		int i = list.size() - 1;
		while (i >= 0 && 
				(((MetaNode)list.get(i)).getModelElement() instanceof InteractionUse ||
						((MetaNode)list.get(i)).getModelElement() instanceof Comment)) {
			i--;
		}
		list.add(i + 1, this.node);
		this.node.setParent(fatherNode);
	}
}
